<template>
    <div class="dzs-form-data-copy-and-paste">
        <dzs-button type='primary' text @click="copyData">
            <el-icon><DocumentCopy /></el-icon>
            <span>复制表单数据</span>
        </dzs-button>
        <dzs-button  type='primary' text @click="pasteData">
            <el-icon><Document /></el-icon>
            <span>粘贴表单数据</span>
        </dzs-button>
    </div>
</template>

<script setup lang="ts">
import { DocumentCopy, Document } from '@element-plus/icons-vue'
import {copyToClipboard} from "../tool";
import type { formItemInstance } from "../@types";
import tool from "@/utils";
import { ElMessage , ElMessageBox } from 'element-plus';

const emit = defineEmits(['paste'])

const props = defineProps<{
    formData: Record<string, any>;
    simple: string;
    formItem: formItemInstance[];
}>();
/**复制*/
const copyData = () => {
    let formData = tool.deepCopy(props.formData);
    props.formItem.forEach((item) => {
        if (item.isHidden) {
            formData[item.key] = ""
        }
    })
    formData = transformKeysToNestedObject(formData);
    localStorage.setItem('dzs-form-data-copy', JSON.stringify({
        formData: formData,
        simple: props.simple
    }))
    copyToClipboard(JSON.stringify(formData));
    ElMessage.success('标准组件值拷贝成功!')
}

/**粘贴*/
const pasteData = () => {
    let data = localStorage.getItem('dzs-form-data-copy');
    if (!data) {
        ElMessage.error('没有复制的内容');
        return;
    }
    let paste_date = JSON.parse(data) as { formData: Record<string, any>, simple: string };
    if (paste_date.simple != props.simple) {
        ElMessage.error('复制的内容和当前表单不一致');
        return;
    }
    ElMessageBox.confirm('是否覆盖当前表单内容?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        emit('paste', paste_date.formData)
    }).catch(() => { })
}

/**格式化值*/
const transformKeysToNestedObject = (obj: Record<string, any>) => {
    let result = {};

    // 获取对象的所有键（避免在for-in循环中检查hasOwnProperty）  
    const keys = Object.keys(obj);

    for (let i = 0; i < keys.length; i++) {
        const keyPath = keys[i].split('.');
        const value = obj[keys[i]];
        let currentNode: any = result;

        // 遍历嵌套键数组，除了最后一个键  
        for (let j = 0; j < keyPath.length - 1; j++) {
            const currentKey = keyPath[j];

            // 使用逻辑或运算符来避免额外的检查  
            currentNode = currentNode[currentKey] || (currentNode[currentKey] = {});
        }

        // 将最后一个键和值赋给当前节点  
        currentNode[keyPath[keyPath.length - 1]] = value;
    }

    return result;
}
</script>
<style lang="scss" scoped>
.dzs-form-data-copy-and-paste {
    display: flex;
    justify-content: flex-end;
}
</style>